#!/bin/bash
source $DRAW_INI
source $DRAW_CFG

rm -f s_${1}_merged_nodup_uniq_recal.ba?
if [ -s s_${1}_nodup_uniq_recal.FULL.bam ];then exit 0;fi

#
# Picard (MergeSamFiles.jar)  INPUT Argument does not allow wildcards.
#                             here we make a long string of INPUT=
INPUT_STR=""

for f in $(ls s_${1}_nodup_uniq_recal.chr*.bam 2> /dev/null)
do
 INPUT_STR=$INPUT_STR"INPUT=$f "
done;

java -Xmx2g \
 -jar $GENOMICS_JAR/MergeSamFiles.jar \
 $INPUT_STR \
 OUTPUT=s_${1}_merged_nodup_uniq_recal.bam \
 CREATE_INDEX=true \
 VALIDATION_STRINGENCY=SILENT \
 TMP_DIR=$TMPDIR \
 SORT_ORDER=coordinate \
 USE_THREADING=false 

EXITSTATUS=$?

if [ ! -s s_${1}_merged_nodup_uniq_recal.bam ];then exit 100;fi;

# throw error if output file < 1GB
#if [ $(stat --printf="%s" "s_${1}_merged_nodup_uniq_recal.bam") -le 1024000000 ]
#then
#   echo "BAM file is too small"
#   exit 100
#fi

# throw error if output file < nodup_uniq file
SIZE1=$(stat --printf="%s" "s_${1}_merged_nodup_uniq_recal.bam")
SIZE2=$(stat --printf="%s" "s_${1}_nodup_uniq.bam")

#if [ $SIZE1 -le $SIZE2 ]
#then
#   echo "Size Error"
#   exit 100
#fi

# Check BAM EOF
BAM_28=$(tail -c 28 s_${1}_merged_nodup_uniq_recal.bam|xxd -p)
if [ "$MAGIC28" != "$BAM_28" ]
then
  echo "Error with EOF" 
  exit 100
fi

exit $EXITSTATUS
